<template>
	<view class="container">

		<view class="user-info-card">

			<view class="info-row">
				<text class="row-label">头像</text>
				<view class="row-content avatar-content" @click="getlabel">
					<image class="user-avatar" :src="userInfo.avatar_url || '/static/logo.png'" mode="aspectFill"></image>
				</view>
			</view>
			
			<view class="info-row">
				<text class="row-label">昵称</text>
				<view class="row-content">
					<input class="item-input" v-model="userInfo.nickname" />
				</view>
			</view>
		
			<view class="info-row">
				<text class="row-label">ID</text>
				<view class="row-content">
					<text class="item-text">{{ userInfo.openid || '未获取到ID' }}</text>
				</view>
			</view>
			
			<view class="info-row" @click="showCountryPicker" id="countryRow">
				<text class="row-label">国家</text>
				<view class="row-content">
					<text class="item-text">{{ userInfo.country || '请选择' }}</text>
				</view>
			</view>
			
			<!-- 国家选择器 -->
			<view v-if="showCountryPopup" class="custom-popup" :style="{top: countryPopupTop + 'px'}">
				<view class="popup-content">
					<view class="popup-header">
						<text class="popup-title">选择国家</text>
						<text class="popup-close" @click="closeCountryPicker">完成</text>
					</view>
					<picker-view :value="countryIndex" @change="onCountryChange" class="picker-view">
						<picker-view-column>
							<view class="picker-item" v-for="(item, index) in countries" :key="index">{{ item }}</view>
						</picker-view-column>
					</picker-view>
				</view>
			</view>
			
			<view class="info-row" @click="showProvincePicker" id="provinceRow">
				<text class="row-label">省份</text>
				<view class="row-content">
					<text class="item-text">{{ userInfo.province || '请选择' }}</text>
				</view>
			</view>
			
			<!-- 省份选择器 -->
			<view v-if="showProvincePopup" class="custom-popup" :style="{top: provincePopupTop + 'px'}">
				<view class="popup-content">
					<view class="popup-header">
						<text class="popup-title">选择省份</text>
						<text class="popup-close" @click="closeProvincePicker">完成</text>
					</view>
					<picker-view :value="provinceIndex" @change="onProvinceChange" class="picker-view">
						<picker-view-column>
							<view class="picker-item" v-for="(item, index) in provinces" :key="index">{{ item }}</view>
						</picker-view-column>
					</picker-view>
				</view>
			</view>
			
			<view class="info-row" @click="showgenderPicker" id="genderRow">
				<text class="row-label">年龄</text>
				<view class="row-content">
					<text class="item-text">{{ userInfo.gender || '请选择' }}</text>
				</view>
			</view>
			
			<!-- 年龄选择器 -->
			<view v-if="showgenderPopup" class="custom-popup" :style="{top: genderPopupTop + 'px'}">
				<view class="popup-content">
					<view class="popup-header">
						<text class="popup-title">选择年龄</text>
						<text class="popup-close" @click="closegenderPicker">完成</text>
					</view>
					<picker-view :value="genderIndex" @change="ongenderChange" class="picker-view">
						<picker-view-column>
							<view class="picker-item" v-for="(item, index) in genders" :key="index">{{ item }}</view>
						</picker-view-column>
					</picker-view>
				</view>
			</view>
		</view>
		
		<view class="save-section">
			<button class="save-btn" @click="saveProfile">保存</button>
		</view>

		<wx-user-info-modal
            :value="showAuthorizationModal"
			@input="val => showAuthorizationModal = val"
			@updated="updatedUserInfoEvent"
			:animation="false"
      	></wx-user-info-modal>

	</view>
</template>

<script>
	import config from '@/config/api.js'
	import wxUserInfoModal from '@/uni_modules/tuniaoui-wx-user-info/components/tuniaoui-wx-user-info/tuniaoui-wx-user-info.vue'	

	export default {
        components: {
            wxUserInfoModal
        },
        data() {
			return {
				userInfo: {
					// avatar_url: null,
                    // city: null,
                    // country: "",
                    // create_time: "",
                    // gender: 0,
                    // id: "",
                    // langugeage: null,
                    // nickname: "",
                    // openid: "",
                    // province: "",
                    // update_time: ""
				},
				countries: ['中国', '美国', '英国', '法国', '德国', '日本', '韩国', '澳大利亚', '加拿大', '新加坡'],
				countryIndex: [0],
				provinces: ['请选择国家'],
				provinceIndex: [0],
				genders: Array.from({length: 100}, (v, k) => k + 1), // 1~100的数组
				genderIndex: [0],
				showCountryPopup: false,
				showProvincePopup: false,
				showgenderPopup: false,
				countryPopupTop: 0,
				provincePopupTop: 0,
				genderPopupTop: 0,
				showAuthorizationModal: false,
			}
		},
		onLoad() {
			// 页面加载时获取用户信息
			this.loadUserInfo();
		},
		onUnload() {
		},
		methods: {
			// 加载用户信息
			loadUserInfo() {
				try {
					const storedInfo = uni.getStorageSync('userInfo');
					if (storedInfo) {
						this.userInfo = storedInfo;
						// 根据已保存的国家更新省份列表
						if (this.userInfo.country) {
							this.updateProvinces();
							// 确保省份字段正确显示
							if (this.userInfo.province) {
								const provinceIndex = this.provinces.indexOf(this.userInfo.province);
								if (provinceIndex !== -1) {
									this.provinceIndex = [provinceIndex];
								}
							}
						}
						// 如果已保存年龄，设置年龄索引
						if (this.userInfo.gender) {
							const genderIndex = this.genders.indexOf(parseInt(this.userInfo.gender));
							if (genderIndex !== -1) {
								this.genderIndex = [genderIndex];
							}
						}
					}
				} catch (e) {
					console.error('获取用户信息失败', e);
				}
                // console.log(this.userInfo);
			},

			getlabel(){
				this.showAuthorizationModal = true;
			},
			updatedUserInfoEvent(e){
				console.log('实例',e);
				console.log(this.userInfo);				
				this.userInfo.avatar_url = e.avatar;
				this.userInfo.nickname = e.nickname;
			},
			// 显示国家选择器
			showCountryPicker(e) {
				// 获取点击元素的位置
				const query = uni.createSelectorQuery();
				query.select('#countryRow').boundingClientRect(data => {
					if (data) {
						// 设置弹窗位置在元素下方
						this.countryPopupTop = data.top + data.height;
						this.showCountryPopup = true;
						// 隐藏其他弹窗
						this.showProvincePopup = false;
						this.showgenderPopup = false;
					}
				}).exec();
			},
			
			// 关闭国家选择器
			closeCountryPicker() {
				this.showCountryPopup = false;
			},
			
			// 国家选择变化
			onCountryChange(e) {
				this.countryIndex = e.detail.value;
				this.userInfo.country = this.countries[this.countryIndex[0]];
				
				// 根据国家更新省份列表
				this.updateProvinces();
			},
			
			// 更新省份列表
			updateProvinces() {
				if (this.userInfo.country === '中国') {
					this.provinces = ['北京市', '上海市', '天津市', '重庆市', '河北省', '山西省', '辽宁省', '吉林省', '黑龙江省', '江苏省', '浙江省', '安徽省', '福建省', '江西省', '山东省', '河南省', '湖北省', '湖南省', '广东省', '海南省', '四川省', '贵州省', '云南省', '陕西省', '甘肃省', '青海省', '台湾省', '内蒙古自治区', '广西壮族自治区', '西藏自治区', '宁夏回族自治区', '新疆维吾尔自治区', '香港特别行政区', '澳门特别行政区'];
				} else if (this.userInfo.country === '美国') {
					this.provinces = ['加利福尼亚州', '纽约州', '德克萨斯州', '佛罗里达州', '伊利诺伊州', '宾夕法尼亚州', '俄亥俄州', '密歇根州', '乔治亚州', '北卡罗来纳州'];
				} else {
					this.provinces = ['暂无数据'];
				}
				
				// 检查当前选择的省份是否在新的省份列表中
				const currentProvinceIndex = this.provinces.indexOf(this.userInfo.province);
				if (currentProvinceIndex !== -1) {
					// 如果当前选择的省份在列表中，保持选择
					this.provinceIndex = [currentProvinceIndex];
				} else {
					// 否则重置为第一个选项
					this.provinceIndex = [0];
					this.userInfo.province = this.provinces[0];
				}
			},
			
			// 显示省份选择器
			showProvincePicker(e) {
				if (!this.userInfo.country) {
					uni.showToast({
						title: '请先选择国家',
						icon: 'none'
					});
					return;
				}
				
				// 获取点击元素的位置
				const query = uni.createSelectorQuery();
				query.select('#provinceRow').boundingClientRect(data => {
					if (data) {
						// 设置弹窗位置在元素下方
						this.provincePopupTop = data.top + data.height;
						this.showProvincePopup = true;
						// 隐藏其他弹窗
						this.showCountryPopup = false;
						this.showgenderPopup = false;
					}
				}).exec();
			},
			
			// 关闭省份选择器
			closeProvincePicker() {
				this.showProvincePopup = false;
			},
			
			// 省份选择变化
			onProvinceChange(e) {
				this.provinceIndex = e.detail.value;
				this.userInfo.province = this.provinces[this.provinceIndex[0]];
			},
			
			// 显示年龄选择器
			showgenderPicker(e) {
				// 获取点击元素的位置
				const query = uni.createSelectorQuery();
				query.select('#genderRow').boundingClientRect(data => {
					if (data) {
						// 设置弹窗位置在元素下方
						this.genderPopupTop = data.top + data.height;
						this.showgenderPopup = true;
						// 隐藏其他弹窗
						this.showCountryPopup = false;
						this.showProvincePopup = false;
					}
				}).exec();
			},
			
			// 关闭年龄选择器
			closegenderPicker() {
				this.showgenderPopup = false;
			},
			
			// 年龄选择变化
			ongenderChange(e) {
				this.genderIndex = e.detail.value;
				this.userInfo.gender = this.genders[this.genderIndex[0]];
			},
			
			// 保存资料到数据库
			async saveProfile() {
				// 获取 openid 用于更新用户信息
				const openid = this.userInfo.openid || uni.getStorageSync('openid');
				
				if (!openid) {
					uni.showToast({
						title: '用户信息异常',
						icon: 'none'
					});
					return;
				}
				
				try {
					// 通过 PUT 请求将用户资料保存到数据库
					const res = await uni.request({
						url: config.baseUrl + config.api.users + '/' + this.userInfo.id,
						method: 'PUT', 
						data: {
							id: this.userInfo.id,
							openid: this.userInfo.openid,
							nickname: this.userInfo.nickname,
							avatar_url: this.userInfo.avatar_url,
							country: this.userInfo.country,
							province: this.userInfo.province,
							gender: this.userInfo.gender,
							// 可以添加其他需要保存的字段
							updated_at: new Date().toISOString()
						}
					});
					
					if (res.statusCode === 200 || res.statusCode === 201) {
						// 数据库保存成功后，同步保存至全局数据信息
						uni.setStorageSync('userInfo', this.userInfo);
						
						uni.showToast({
							title: '保存成功',
							icon: 'success'
						});
						
						// 返回上一页
						setTimeout(() => {
							uni.navigateBack();
						}, 1000);
					} else {
						// 解析错误消息
						let errorMsg = '保存失败';
						if (res.data && res.data.messgender) {
							errorMsg = res.data.messgender;
						} else if (res.data && typeof res.data === 'string') {
							errorMsg = res.data;
						} else if (res.statusCode === 405) {
							errorMsg = '请求方法不被允许';
						} else {
							errorMsg = '保存失败: ' + (res.data.messgender || '未知错误');
						}
						
						uni.showToast({
							title: errorMsg,
							icon: 'none'
						});
						console.error('保存用户信息失败', res);
					}
				} catch (e) {
					uni.showToast({
						title: '网络错误',
						icon: 'none'
					});
					console.error('保存用户信息异常', e);
				}
			}
		}
	}
</script>

<style scoped>
	.container {
		background-color: #f8f8f8;
		min-height: 100vh;
		padding: 20rpx;
	}
	
	.user-header {
		background-color: white;
		padding: 30rpx;
		margin-bottom: 20rpx;
		border-radius: 10rpx;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
		text-align: center;
	}
	
	.pgender-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}
	
	.user-info-card {
		background-color: white;
		border-radius: 10rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
		position: relative;
	}
	
	.info-row {
		display: flex;
		align-items: center;
		padding: 10rpx 0;
		border-bottom: 1rpx solid #eee;
		min-height: 60rpx;
	}
	
	.info-row:last-child {
		border-bottom: none;
	}
	
	.row-label {
		width: 120rpx;
		font-size: 32rpx;
		color: #333;
		flex-shrink: 0;
	}
	
	.row-content {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: flex-end;
	}
	
	.avatar-content {
		justify-content: flex-end;
	}
	
	.user-avatar {
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
	}
	
	.item-input, .item-textarea {
		width: 100%;
		padding: 10rpx;
		font-size: 28rpx;
		box-sizing: border-box;
		text-align: right;
		border: none;
		outline: none;
		background: transparent;
	}
	
	.item-input:focus {
		border: none;
		outline: none;
	}
	
	.item-textarea {
		height: 150rpx;
		resize: none;
	}
	
	.item-text {
		font-size: 28rpx;
		color: #999;
		text-align: right;
	}
	
	.save-section {
		padding: 10rpx 20rpx;
		min-height: 60rpx;
	}
	
	.save-btn {
		background-color: #f0ad4e;
		color: white;
		border: none;
		border-radius: 10rpx;
		font-size: 32rpx;
		padding: 10rpx;
		width: 100%;
		height: 75rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	/* 自定义弹窗样式 */
	.custom-popup {
		position: absolute;
		left: 0;
		right: 0;
		z-index: 999;
		background-color: #fff;
		border-radius: 20rpx;
		margin: 0 20rpx;
		box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.1);
	}
	
	.popup-content {
		padding: 20rpx;
	}
	
	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #eee;
	}
	
	.popup-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}
	
	.popup-close {
		color: #f0ad4e;
		font-size: 28rpx;
	}
	
	.picker-view {
		height: 400rpx;
		margin-top: 20rpx;
	}
	
	.picker-item {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 80rpx;
		font-size: 30rpx;
	}
</style>